import React from 'react';
import PropTypes from 'prop-types';
import {Button, Form, Row, Col, Card} from 'antd';
import {FORM_OPTIONS} from '../constants';
import {PERMISSION} from './constants';
import {customerType, dealerType} from '../Enum';
import WrappedSelect from '../common/WrappedSelect';
import DateRangePicker from 'Shared/components/DateRangePicker';
import DealerSelectPanel from '../common/DealerSelect/SelectEdit';
import TextInput from 'Shared/components/TextInput';
import Export from '../common/Export';
import {injectIntl, language} from './intl';
import ImportPanel from './ImportPanel';
import MultipleSelect from '../common/MultipleSelect';
const FormItem = Form.Item;

const dealerConditions = {
    type: dealerType.经销商
};
const customerTypeToList = customerType.toList(language);
class QueryPanel extends React.PureComponent {
    state = {
        data: {},
        showImportPanel: false
    }
    handleFilterChange = (value, name) => {
        this.props.onConditionsChange(name, value);
    }

    handleFilterPressEnter = (value, name) => {
        this.props.onConditionsChange(name, value);
        this.props.querySearch();
    }
    onSelectDealer = data => {
        this.handleFilterChange(data.id, 'dealerId');
        this.props.onSelect({
            id: data.id,
            code: data.code,
            name: data.name,
        });
    }
    onSelectSubDealer = data => {
        this.handleFilterChange(data.id, 'subDealerId');
        this.props.onSelectSub({
            id: data.id,
            code: data.code,
            name: data.name,
        });
    }
    onChangeImport = () => {
        this.setState({
            showImportPanel: true
        });
    }
    onImportChange = data => {
        if(data)
            this.setState({
                showImportPanel: false
            });
    }
    onCloseImportPanel = () => {
        this.setState({
            showImportPanel: false
        });
    }
    render() {
        const {formatMessage} = this.props.intl;
        const {brands} = this.props.initEnumData;
        const condition = this.props.conditions || {};
        const dealerInfo = condition.dealerId ? {
            id: this.props.queryDealer.id,
            code: this.props.queryDealer.code,
            name: this.props.queryDealer.name
        } : null;
        const subDealerInfo = condition.subDealerId ? {
            id: this.props.querySubDealer.id,
            code: this.props.querySubDealer.code,
            name: this.props.querySubDealer.name
        } : null;
        return (
            <div>
                <Form className="form-standard">
                    <Card>
                        <Row>
                            {brands.length !== 1 && <Col {...FORM_OPTIONS.col}><FormItem label={formatMessage({
                                id: 'queryPanel.form.brandId',
                                defaultMessage: '品牌'
                            })}{...FORM_OPTIONS.item}>
                                <WrappedSelect
                                    allowClear
                                    name="brandId"
                                    value={this.props.conditions.brandId}
                                    options={brands}
                                    onChange={this.handleFilterChange}/>
                            </FormItem>
                            </Col>}
                            <Col {...FORM_OPTIONS.col}>
                                <FormItem label={formatMessage({
                                    id: 'queryPanel.form.vin',
                                    defaultMessage: 'VIN'
                                })}{...FORM_OPTIONS.item}>
                                    <TextInput
                                        name="vin"
                                        value={this.props.conditions.vin}
                                        onPressEnter={this.handleFilterPressEnter}
                                        onChange={this.handleFilterChange}/>
                                </FormItem>
                            </Col>
                            <Col {...FORM_OPTIONS.col}>
                                <FormItem label={formatMessage({
                                    id: 'queryPanel.form.type',
                                    defaultMessage: '客户类型'
                                })}{...FORM_OPTIONS.item}>
                                    <WrappedSelect
                                        allowClear
                                        name="type"
                                        options={customerTypeToList}
                                        value={this.props.conditions.type}
                                        onChange={this.handleFilterChange}/>
                                </FormItem>
                            </Col>
                            <Col {...FORM_OPTIONS.col}>
                                <FormItem label={formatMessage({
                                    id: 'queryPanel.form.customerSoldName',
                                    defaultMessage: '客户姓名'
                                })}{...FORM_OPTIONS.item}>
                                    <TextInput
                                        name="customerSoldName"
                                        value={this.props.conditions.customerSoldName}
                                        onPressEnter={this.handleFilterPressEnter}
                                        onChange={this.handleFilterChange}/>
                                </FormItem>
                            </Col>
                            <Col {...FORM_OPTIONS.col}>
                                <FormItem
                                    label={this.props.intl.formatMessage({
                                        id: 'queryPanel.form.filingTime',
                                        defaultMessage: '建档时间'
                                    })}{...FORM_OPTIONS.item}>
                                    <DateRangePicker
                                        name="filingTime"
                                        value={this.props.conditions.filingTime}
                                        onChange={this.handleFilterChange} />
                                </FormItem>
                            </Col>
                            {!this.props.isDealerUser && <Col {...FORM_OPTIONS.col}>
                                <FormItem
                                    label={this.props.intl.formatMessage({
                                        id: 'queryPanel.form.dealerId',
                                        defaultMessage: '总代'
                                    })}
                                    {...FORM_OPTIONS.item}>
                                    <DealerSelectPanel
                                        value={dealerInfo}
                                        onSelect={this.onSelectDealer} />
                                </FormItem>
                            </Col>
                            }
                            {!this.props.isSubDealerUser && <Col {...FORM_OPTIONS.col}>
                                <FormItem
                                    label={this.props.intl.formatMessage({
                                        id: 'queryPanel.form.subDealerId',
                                        defaultMessage: '经销商'
                                    })}
                                    {...FORM_OPTIONS.item}>
                                    <DealerSelectPanel
                                        value={subDealerInfo}
                                        conditions={dealerConditions}
                                        onSelect={this.onSelectSubDealer} />
                                </FormItem>
                            </Col>
                            }
                            <Col {...FORM_OPTIONS.col}>
                                <FormItem
                                    label={this.props.intl.formatMessage({
                                        id: 'queryPanel.form.productCategoryCode',
                                        defaultMessage: '车型编号'
                                    })}
                                    {...FORM_OPTIONS.item}>
                                    <MultipleSelect
                                        name="productCategoryCode"
                                        dataOptions={this.props.categories}
                                        value={this.props.conditions.productCategoryCode}
                                        onBlur={this.handleFilterChange} />
                                </FormItem>
                            </Col>
                        </Row>
                        <Row>
                            <Col span={6}>
                                <Button key="query" type="primary" onClick={this.props.querySearch} loading={this.props.loading}>{formatMessage({
                                    id: 'queryPanel.btn.query',
                                    defaultMessage: '查询'
                                })}</Button>
                                <Button key="clear" onClick={this.props.onResetClick}>{formatMessage({
                                    id: 'queryPanel.btn.reset',
                                    defaultMessage: '重置'
                                })}</Button>
                            </Col>
                            <Col span={18} className="col-align-right">
                                {this.props.exportable && <Export key={PERMISSION.export} exportRequest={this.props.onClickExport} />}
                                {this.props.settlementExport &&
                                    <Export key={PERMISSION.settlementExport} exportButton={this.props.intl.formatMessage({
                                        id: 'queryPanel.btn.settlementButton',
                                        defaultMessage: '结算导出'
                                    })} exportRequest={this.props.onClickSettlementExport} />}
                                {this.props.importable && <Button key="import" onClick={this.onChangeImport}>{formatMessage({
                                    id: 'queryPanel.btn.import',
                                    defaultMessage: '导入'
                                })}</Button>}
                            </Col>
                        </Row>
                    </Card>
                </Form>
                {
                    this.state.showImportPanel &&
                    <ImportPanel
                        selectKey={'1'}
                        onCancel={this.onCloseImportPanel}
                        onImportChange={this.onImportChange} />
                }
            </div>
        );
    }
}

QueryPanel.propTypes = {
    conditions: PropTypes.object.isRequired,
    loading: PropTypes.bool.isRequired,
    querySearch: PropTypes.func.isRequired,
    onClickSettlementExport: PropTypes.func.isRequired,
    onConditionsChange: PropTypes.func.isRequired,
    onResetClick: PropTypes.func.isRequired,
    onSelect: PropTypes.func.isRequired,
    onSelectSub: PropTypes.func.isRequired,
    categories: PropTypes.array,
    intl: PropTypes.object,
    isDealerUser: PropTypes.bool,
    isSubDealerUser: PropTypes.bool,
};

import {connect} from 'react-redux';
import {saveQueryCondition, querySearch, resetQueryPanel, saveQueryDealer, selectSubDealer, exportData, settlementExportData} from './actions';
import selectorFactory from 'Shared/utils/immutableToJsSelectorFactory';
import {createSelector} from 'reselect';

const getinitEnumData = createSelector(
    state => state.getIn(['page', 'domainData', 'init']),
    init => {
        const initData = init.toJS();
        const brands = initData.brands ? initData.brands.map(item => ({
            text: item.name,
            value: item.id
        })) : [];
        return {
            brands
        };
    }
);
const getCategoryData = createSelector(
    state => state.getIn(['page', 'domainData', 'category']),
    init => {
        const initData = init.toJS();
        const categories = initData.data ? initData.data.map(item => ({
            code: item.code
        })) : [];
        return categories;
    }
);
const getConditions = selectorFactory(['page', 'appState', 'queryCondition']);
const getQueryDealer = selectorFactory(['page', 'appState', 'queryDealer']);
const getQuerySubDealer = selectorFactory(['page', 'appState', 'querySubDealer']);
const mapStateToProps = state => ({
    conditions: getConditions(state),
    initEnumData: getinitEnumData(state),
    loading: state.getIn(['page', 'domainData', 'list', 'isFetching']),
    exportable: state.getIn(['page', 'domainData', 'permission', 'data']).includes(PERMISSION.export),
    importable: state.getIn(['page', 'domainData', 'permission', 'data']).includes(PERMISSION.import),
    settlementExport: state.getIn(['page', 'domainData', 'permission', 'data']).includes(PERMISSION.settlementExport),
    queryDealer: getQueryDealer(state),
    querySubDealer: getQuerySubDealer(state),
    isDealerUser: state.getIn((['page', 'domainData', 'init', 'isDealerUser'])),
    isSubDealerUser: state.getIn((['page', 'domainData', 'init', 'isSubDealerUser'])),
    categories: getCategoryData(state),
});

const mapDispatchToProps = dispatch => ({
    onConditionsChange: (name, value) => dispatch(saveQueryCondition(name, value)),
    querySearch: () => dispatch(querySearch()),
    onResetClick: () => dispatch(resetQueryPanel()),
    onSelect: data => dispatch(saveQueryDealer(data)),
    onSelectSub: data => dispatch(selectSubDealer(data)),
    onClickExport: () => dispatch(exportData()),
    onClickSettlementExport: () => dispatch(settlementExportData()),
});

export default connect(mapStateToProps, mapDispatchToProps)(injectIntl(QueryPanel));
